<template>
	<view class="">
		<loading ref="loading"></loading>
		<view class="" @touchmove.stop.prevent="a = false" @catchtouchmove="a = false">
			<view class="" style="">
				<!-- <swiper style="height: 100vh;width: 100vw;" :circular="true" @change="swiperChange" :current="activeCurrent"> -->
					<!-- <swiper-item v-for="(item,index) in detail.images" :key="index"> -->
						<image :src="detail.images[activeCurrent]" @load="play" style="height: 100vh;width: 100vw;display: flex;" mode="aspectFill"></image>
					<!-- </swiper-item> -->
				<!-- </swiper> -->
			</view>
			<!-- <view v-if="tipsShow" style="position: absolute;top: 0;left: 0;width: 100vw;height: 100vh;z-index: 11;" @click="tipsClick">
				<image src="../../static/tips.png" style="width: 100%;height: 100%;display: flex;" mode="aspectFill"></image>
			</view> -->
			
			<models v-if="loginShow"
			title="为了更好的玩机体验，点击下方按钮授权登录吧~"
			:authorize="true"
			btnText="授权登录" 
			@mask="loginShow = false" 
			@close="loginShow = false"></models>
			
			<models v-if="model.show"
			:ad="model.ad" 
			:title="model.title" 
			:btnText="model.btn" 
			:download="model.download" 
			:closeText="model.close" 
			@mask="model.show = false" 
			@close="model.show = false" 
			@plain="plainClick" 
			@save="modelClick"></models>
		</view>
		<view class="bottom openCss"> <!-- :class="cssTran ? 'closeCss' : 'openCss'" -->
			<view class="nav-box">
				<view class="nav-tab" @click="backClick">
					<u-icon name="/static/icon/back.png" :size="44"></u-icon>
					<text>返回</text>
				</view>
				<view class="nav-tab" @click="addView(detail._id,1)">
					<u-icon name="/static/icon/zan.png" :size="42"></u-icon>
					<text>点赞</text>
				</view>
				<view class="nav-tab" @click="winClick(detail._id)">
					<u-icon name="/static/icon/duihuan.png" :size="42"></u-icon>
					<text>下载</text>
				</view>
				<view class="nav-tab" @click="copyClick(detail.code)">
					<u-icon name="/static/icon/copy.png" :size="40"></u-icon>
					<text>口令</text>
				</view>
				<view class="nav-tab">
					<u-icon name="/static/icon/shares_b.png" :size="44"></u-icon>
					<text>分享</text>
					<button open-type="share" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"></button>
				</view>
			</view>
		</view>
		<!-- <view class="u-flex u-row-center u-col-center" style="width: 100vw;height: 100vh;position: fixed;top: 0;left: 0;" v-if="mengShow" @click="mengClick">
			<view class="" style="width: 100%;height: 100%;position: absolute;background-color: rgba(0,0,0,0.6);"></view>
			<image src="/static/meng.png" style="width: 100vw;height: 100vw;position: relative;"></image>
		</view> -->
	</view>
</template>

<script>
	let videoAd = null;
	var w = uni.getSystemInfoSync().windowWidth;
	var h = uni.getSystemInfoSync().windowHeight;
	export default {
		data() {
			return {
				loginShow: false,
				mengShow: false,
				detail: {},
				
				// 下载弹窗
				model: {
					type: '',
					title: '',
					btn: '',
					close: '',
					ad: false,
					download: false,
					show: false,
				},
				
				pageFlag: '',
				likeFlag: false,
				downFlag: false,
				adCount: 0,
				
				indexCurrent: 1,
				activeCurrent: 0,
				w: w,
				h: h,
			}
		},
		async onLoad({id,index,flag}) {
			var that = this
			let meng = uni.getStorageSync("meng")
			if(!meng) that.mengShow = true
			that.indexCurrent = parseInt(index)+1
			that.activeCurrent = parseInt(index)
			that.pageFlag = flag
			await that.getDetail(id)
			if(that.vk.getVuex('$user.userInfo._id')){
				that.getOrderNum()
			}
			that.addView(id)
			// #ifdef MP
			that.adLoad()
			// #endif
		},
		methods: {
			mengClick(){
				var that = this
				uni.setStorageSync("meng","1")
				that.mengShow = false
			},
			play(){
				var that = this
				that.$nextTick(() => {
					that.$refs.loading.closeLoading()
				})
			},
			async getDetail(id){
				var that = this
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/findOne',
					data:{
						dbName: 'bus-wx-cover',
						whereJson: {
							_id: id
						},
						foreignDB: [{
							dbName: "uni-id-users",
							localKey:"user_id",
							foreignKey: "_id",
							as: "user",
							limit: 1
						}]
					}
				});
				if(data.info.status != 1){
					uni.showToast({
						// #ifdef MP-TOUTIAO
						icon: 'fail',
						// #endif
						// #ifndef MP-TOUTIAO
						icon: 'error',
						// #endif
						mask: true,
						duration: 2000,
						title: '该作品暂未上线'
					})
					setTimeout(function(){
						uni.navigateBack()
					},1800)
					return
				}
				if(data.info){
					that.detail = data.info
				}
			},
			async getOrderNum(){
				var that = this
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/kh/count',
					data:{
						dbName: 'bus-wx-order',
						user_id: that.vk.getVuex('$user.userInfo._id'),
						origin: '_ad',
						day: true
					},
				});
				if(data.num > 0) that.adCount = data.num
			},
			backClick(){
				uni.navigateBack()
			},
			homeClick(id){
				uni.navigateTo({
					url: '/pages/write/home?id='+id+'&mode=0'
				})
			},
			swiperChange(e){
				this.indexCurrent = e.detail.current + 1
			},
			copyClick(e) {
				var that = this
				that.$u.toast('敬请期待~');
			},
			async addView(id,on){
				var that = this
				if(on === 1 && that.likeFlag){
					that.$u.toast('让小猫歇一会~');
					return
				}
				that.likeFlag = true
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/addView',
					data:{
						dbName: 'bus-wx-cover',
						id: id
					}
				});
				if(on === 1){
					that.$u.toast('热度+1');
				}
				setTimeout(function(){
					that.likeFlag = false
				},3000)
			},
			async winClick(){
				var that = this
				if(!that.vk.getVuex('$user.userInfo._id')){
					that.loginShow = true
					return
				}
				if(that.downFlag || that.vk.getVuex('$user.userInfo._id')===that.detail.user_id){
					that.downFile()
					return
				}
				let model = await that.vk.myfn.downModel('down', that.adCount)
				if(model.show){
					that.model = model
				}else{
					// 处理订单
					let res = await that.upOrder('free')
					that.downFile()
				}
			},
			async modelClick(){
				var that = this
				if(that.model.type === 'vip'){
					let res = await that.upOrder('vip')
					that.downFile()
				}else if(that.model.type === 'down'){
					let res = await that.upOrder('score')
					that.downFile()
				}else if(that.model.type === 'ad' || that.model.type === 'video'){
					that.adClick()
				}
				that.model.show = false
			},
			plainClick(){
				var that = this
				that.model.show = false
				that.downFile(1)
			},
			async upOrder(origin){
				let that = this;
				uni.showLoading({
					mask: true,
					title: '保存中...'
				})
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/kh/setOrder',
					data:{
						user_id: that.vk.getVuex('$user.userInfo._id'),
						detail_id: that.detail._id,
						type: 'detail',
						origin,
						index: that.indexCurrent-1
					}
				});
				uni.hideLoading()
				that.downFlag = true
				if(data.user) that.vk.setVuex('$user.userInfo.score', data.user.score)
				return data
			},
			adClick(){
				var that = this
				videoAd.show()
			},
			adLoad(){
				var that = this
				let adUnitId = that.vk.getVuex('$setting.client.videos_id')
				if(adUnitId){
					// 加载激励视频广告
					videoAd = uni.createRewardedVideoAd({
						adUnitId: adUnitId
					});
					//捕捉错误
					videoAd.onError(err => {
						// 进行适当的提示
						switch (err.errCode) {
							case 1004:
								videoAd.load()
								videoAd.show()
								break;
							default:
								that.$u.toast('广告拉取失败，请稍后再试！')
						}
					});
					// 监听关闭
					videoAd.onClose((status) => {
						if (status.isEnded) {
							// 正常播放结束，下发奖励
							that.adDown()
						} else {
							// 播放中途退出，进行提示
							that.$u.toast('中途退出，无法获得奖励！');
						}
					});
					videoAd.load();
				}
			},
			async adDown(){
				var that = this
				if(that.model.type === 'video'){
					uni.showLoading({
						mask: true,
						title: '加载中...'
					})
					// 请求后台增加积分
					let res = await that.vk.myfn.upScore(that.vk.getVuex('$user.userInfo._id'),'video','观看视频广告')
					uni.hideLoading()
					// 看完广告  增加积分
					that.model.type = 'colse'
					that.model.title = "<div style='padding-top: 10px;'>观看成功，恭喜你获得<span class='num' style='color: "+that.vk.getVuex('$app.config.color.sec')+"'>"+res.score+"</span>"+that.vk.getVuex('$setting.score.name')+"，当前有<span class='num' style='color: "+that.vk.getVuex('$app.config.color.sec')+"'>"+that.vk.getVuex('$user.userInfo.score')+"</span>"+that.vk.getVuex('$setting.score.name')+"，赶紧去下载吧~</div>"
					that.model.btn = '我知道了'
					that.model.close = ' '
					that.model.ad = false
					that.model.download = false
					that.model.show = true
				}else if(that.model.type === 'ad'){
					// 处理订单
					let res = await that.upOrder('ad')
					that.downFile()
				}
			},
			downFile(on){
				var that = this
				uni.showLoading({
					mask: true,
					title: '保存中...'
				})
				let url = that.detail.images[that.indexCurrent-1]
				let extension = url.substring(url.lastIndexOf('.') + 1)
				let fileName = new Date().valueOf()
				if(on===1) url = url + '?x-oss-process=image/resize,m_lfit,w_200'
				uni.downloadFile({
					url: url,
					// #ifdef MP-WEIXIN
					filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.' + extension,
					// #endif
					success: (res) => {
						// #ifdef MP-WEIXIN
						var benUrl = res.filePath
						// #endif
						// #ifndef MP-WEIXIN
						var benUrl = res.tempFilePath
						// #endif
						//图片保存到本地相册
						uni.saveImageToPhotosAlbum({
							filePath: benUrl,
							//授权成功，保存图片
							success: function(data) {
								uni.hideLoading()
								that.model.type = 'share'
								that.model.title = '已成功保存到系统相册，别忘了分享给朋友也来下载哦！'
								that.model.btn = '分享给好友'
								that.model.close = '再想想看'
								that.model.ad = true
								that.model.download = false
								that.model.show = true
							},
							//授权失败
							fail: function(err) {
								uni.hideLoading()
								if (err.errMsg) {
									//重新授权弹框确认
									uni.showModal({
										title: '温馨提示',
										content: '打开相册权限后下载！',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success() {}
												});
											}
										}
									});
								}
							}
						});
					},
					fail: (error) => {
						console.log(error)
					}
				})
			},
			// 授权登录
			getUserInfo(){
				var that = this
				that.loginShow = false
				uni.showLoading({
					mask: true,
					title: '授权中...'
				})
				uni.getUserProfile({
				    desc: '更新您的个人信息',
				    success: async (res) => {
						uni.hideLoading()
						uni.login({
							success: async function({code}) {
								let data = await that.vk.myfn.userLogin(code,res.userInfo)
								if(data.code === 0){
									that.getOrderNum()
								}
							},
						});
				    },
				    fail(err){
						uni.hideLoading()
					    uni.showToast({
							icon: 'none',
							title: '授权失败',
							duration: 1500
					    })
				    }
				})
			},
		},
		onShareAppMessage(res) {
			setTimeout(function(){
				this.model.show = false
			},2000)
			return {
				title: '这里有超多好看的壁纸免费下载~',
				imageUrl: this.detail.images[this.indexCurrent-1],
				path: 'pages/index/index?inviteId='+(this.vk.getVuex('$user.userInfo._id')?this.vk.getVuex('$user.userInfo._id'):'')+'&detailId='+this.detail._id+'&index='+(this.indexCurrent-1)+'&type=detail'
			}
		}
	}
</script>
<style lang="scss" scoped>
	.bottom {
		position: fixed;
		left: 4%;
		right: 0;
		width: 92%;
		height: 52px;
		box-shadow: 0 0px 8px rgba(31,31,31, 0.08);
		background: rgba(31,31,31, 0.95);
		border-radius: 49px;
		opacity: 0.8;
		.num{
			position: absolute;
			top: -20rpx;
			top: -70rpx;
			left: 44%;
			background: rgba(0,0,0,0.6);
			color: #FFF;
			padding: 4rpx 20rpx;
			font-size: 12px;
			border-radius: 36px;
		}
		.user{
			animation: tiaobig 4s ease-in-out alternate infinite;
			position: absolute;
			top: -75rpx;
			right: 0%;
			background: rgba(31, 31, 31, 0.95);
			color: #FFF;
			height: 50rpx;
			padding: 0 30rpx 0 0;
			font-size: 14px;
			border-radius: 70rpx;
			.nick{
				position: relative;
				top: -1px;
				max-width: 180rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}
	@keyframes tiaobig {
		40% {
			transform: scale(1);
		}
		44% {
			transform: scale(1.06);
		}
		48% {
			transform: scale(0.96);
		}
		52% {
			transform: scale(1.04);
		}
		56% {
			transform: scale(0.98);
		}
		60% {
			transform: scale(1);
		}
	}

	.nav-tab {
		position: relative;
		width: 100%;
		height: 52px;
		font-size: 12px;
		color: #D8D8D8;
		font-weight: 400;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.nav-box {
		/* position: absolute; */
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		width: 100%;
		box-sizing: border-box;
	}

	.openCss {
		animation-name: openLinear;
		// animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: 40px;
	}

	@keyframes openLinear {
		0% {
			transform: translateY(92px);
		}
		100% {
			transform: translateY(0px);
		}
	}

	.closeCss {
		animation-name: closeLinear;
		animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: -52px;
	}

	@keyframes closeLinear {
		0% {
			transform: translateY(-92px);
		}
		100% {
			transform: translateY(0px);
		}
	}
	
	.u-indicator-item-number {
		padding: 6rpx 16rpx;
		line-height: 1;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 100rpx;
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
	}
	.hover-class{
		transform:scale(0.95);
		transition: all 0.2s;
	}
	
	/deep/ .num{
		font-size: 16px;
		font-weight: 700;
		padding: 0 8rpx;
	}
</style>